<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>暂时没有接触过java 所以通过ai助手转换成了js代码 还原度不高 但模拟了Snowflake算法的核心思想</h1>
    <script>
        class SnowflakeIdGenerator {
            constructor(datacenterId, workerId, sequence = 0, epoch = 1288834974657) {
                this.datacenterId = datacenterId & 0x1F; // 最多支持5位数据中心ID  
                this.workerId = workerId & 0x1F;         // 最多支持5位机器ID（或工作节点ID）  
                this.sequence = sequence;
                this.lastTimestamp = -1;
                this.epoch = epoch; // 自定义纪元时间戳（例如Twitter的Snowflake使用的纪元是2010-11-04 09:42:54.657）  
            }

            // 模拟系统时间（在实际应用中，您应该使用高精度的时钟源）  
            currentTimeMillis() {
                return Math.floor(Date.now() - this.epoch);
            }

            // 生成下一个ID  
            nextId() {
                let timestamp = this.currentTimeMillis();

                if (timestamp < this.lastTimestamp) {
                    throw new Error('Clock moved backwards. Refusing to generate id');
                }

                if (this.lastTimestamp === timestamp) {
                    this.sequence = (this.sequence + 1) & 0xFFF; // 序列号是12位的  
                    if (this.sequence === 0) {
                        timestamp = this.tilNextMillis(this.lastTimestamp);
                    }
                } else {
                    this.sequence = 0;
                }

                this.lastTimestamp = timestamp;

                // ID的组成部分：  
                // (timestamp - epoch) << 22 | (datacenterId << 17) | (workerId << 12) | sequence  
                return ((timestamp - this.epoch) << 22) |
                    (this.datacenterId << 17) |
                    (this.workerId << 12) |
                    this.sequence;
            }

            // 等待直到下一毫秒  
            tilNextMillis(lastTimestamp) {
                let timestamp = this.currentTimeMillis();
                while (timestamp <= lastTimestamp) {
                    timestamp = this.currentTimeMillis();
                }
                return timestamp;
            }
        }

        // 使用示例  
        const idGenerator = new SnowflakeIdGenerator(1, 1);
        for (let i = 0; i < 10; i++) {
            const id = idGenerator.nextId().toString(36); // 转换为36进制以便更短地显示     
            console.log(id);  
        }
    </script>
</body>

</html>